
package com.wwy.monitor.service.acl.helper;

import com.alibaba.buc.api.AccessControlService;
import com.alibaba.buc.api.check.CheckPermissionParam;
import com.alibaba.buc.api.check.CheckPermissionResult;
import com.alibaba.buc.api.exception.BucException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @class: PermissionServiceHelper
 * @description: acl ä¸­çæééªè¯
 * @author: jl107065 jl107065@alibaba-inc.com
 * @date: 16/4/26 ä¸å1:34
 */
@Service("acl_permissionServiceHelper")
public class PermissionServiceHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(PermissionServiceHelper.class);
    @Autowired
    private AccessControlService accessControlService;

    /**
     * æ£æ¥ç¨æ·æ¯å¦æACLç¸å³æé
     *
     * @param userId         BUC ç¨æ·id éç¨æ·å·¥å·
     * @param permissionName ACLæéåç§°
     * @return Boolean
     */
    public Boolean hasPermissionOf(Long userId, String permissionName) {
        if (userId == null) {
            return false;
        }
        if (accessControlService == null) {
            return true;
        }
        boolean result = false;
// åå»ºå¥å
        CheckPermissionParam checkPermissionParam = new CheckPermissionParam();
// è®¾ç½® userId
        checkPermissionParam.setUserId(userId.intValue());
        List<String> permissionNames = new ArrayList<String>();
// è®¾ç½®å¨ ACL åå°éç½®çæéå
        permissionNames.add(permissionName);
        checkPermissionParam.setPermissionNames(permissionNames);
        try {
            List<CheckPermissionResult> results = accessControlService.checkPermissions(checkPermissionParam);
            if (results != null && results.size() > 0) {
                result = results.get(0).isAccessible();
            }
        } catch (BucException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;
    }
}